"""
新拖拽两圆逻辑。
对数据处理，进行解耦和优化。
"""
from __future__ import annotations

import math

import arcade


SCREEN_WIDTH=800
SCREEN_HEIGHT=600
SCREEN_TITLE='拖拽两圆'

CIRCLE_RADIUS=30

class MyCircle:
    def __init__(self,x,y,r=CIRCLE_RADIUS,dragging=False):
        """ 初始化 """
        self.x=x
        self.y=y
        self.r=r
        self.dragging=dragging
        pass

    def is_inner(self,x,y)->bool:
        """
        坐标是否在园内
        """
        dx=x-self.x
        dy=y-self.y
        return math.sqrt(dx**2+dy**2)<=self.r
    
    def ref_other(self,other:MyCircle)->int:
        """ 
        和另一个圆的关系 
        -1:相交
        0:相切
        1:相离
        """
        dx=self.x-other.x
        dy=self.y-other.y
        distance=math.sqrt(dx**2+dy**2)
        sum_r=self.r+other.r
        if distance>sum_r:
            return 1
        elif distance==sum_r:
            return 0
        else:
            return -1
        
    def deal_collide(self,other:MyCircle)->None:
        """
        处理碰撞
        暂时仅考虑圆
        """
        dx=self.x-other.x
        dy=self.y-other.y
        distance=math.sqrt(dx**2+dy**2)
        sum_r=self.r+other.r
        if distance<sum_r:
            """
            原方向比例弹出
            """
            if distance==0:
                self.x=self.x+sum_r
            else:
                scale=sum_r/distance
                self.x=other.x+dx*scale
                self.y=other.y+dy*scale
        pass



class DraggableCircles(arcade.Window):

    def __init__(self):
        super().__init__(SCREEN_WIDTH,SCREEN_HEIGHT,SCREEN_TITLE)
        arcade.set_background_color(arcade.color.BLACK)

        self.circles=[MyCircle(200,300),MyCircle(600,300,50)]

    def on_draw(self):
        self.clear()
        for circle in self.circles:
            arcade.draw_circle_filled(circle.x,circle.y,circle.r,arcade.color.WHITE)


    def on_mouse_press(self, x, y, button, modifiers):
        for c in self.circles:
            if c.is_inner(x,y):
                c.dragging=True

    def on_mouse_release(self, x, y, button, modifiers):
        for c in self.circles:
            c.dragging=False

    def on_mouse_drag(self, x, y, dx, dy, buttons, modifiers):
        for c in self.circles:
            if not c.dragging:
                continue

            c.x=x
            c.y=y
            for other in self.circles:
                if other is c:
                    continue

                c.deal_collide(other)


def main():
    window=DraggableCircles()
    arcade.run()

if __name__=='__main__':
    main()
